/*
 * @Description: 工具栏配置
 * @Author: HuiSir<https://gitee.com/huisir001>
 * @Date: 2025-08-04 19:17:37
 * @LastEditTime: 2025-09-16 17:36:57
 */
import { defineToolsOptions } from "@/components/TablePage/predefined";
import { IFormOption } from "@/ui";
import useEditOptions from "./useEditOptions";
import useSearchOptions from "./useSearchOptions";
import { removeFileById, update } from "@/api/file/index";
import { getImageInfoByFile } from "@/utils/common";

export default defineToolsOptions(
  (getGroupOptions: (formOptions: IFormOption[]) => Promise<void>) => ({
    tools: ["add", "delete", "search", "export", "refresh", "cols"],
    searchFormParams: {},
    searchFormOptions: useSearchOptions(),
    beforeSearchFormLoad(_formData, formOptions) {
      return getGroupOptions(formOptions.value);
    },
    addRequest: update,
    delRequest: removeFileById,
    addFormOptions: useEditOptions(),
    addDialogProps: { title: "新增文件" },
    beforeShowAddDialog: async (_formData, formOptions) => {
      formOptions.value.forEach((option) => {
        if (option.key !== "url") {
          option.hide = true;
        } else {
          option.props!.listType = "text";
        }
      });

      // 类目列表
      await getGroupOptions(formOptions.value);
    },
    getParamsBeforeDelete(selection) {
      return selection.map((item) => item.id).join(",");
    },
    uploadChange(uploadParams, form) {
      // 若为删除（因为仅有一个文件,可以这样判断）
      if (!uploadParams.uploadFile) {
        form.options.value.forEach((option) => {
          if (option.key !== "url") {
            option.hide = true;
          } else {
            option.props!.listType = "text";
          }
        });
      } else {
        form.options.value.forEach((option) => {
          if (
            option.key !== "url" &&
            option.key !== "width" &&
            option.key !== "height"
          ) {
            option.hide = false;
          }
        });
        // 获取文件大小及名称
        form.data.value.name = uploadParams.uploadFile.name;
        form.data.value.size = uploadParams.uploadFile.size;
      }
      // 若为图片，则获取图片宽高
      if (uploadParams.uploadFile?.raw?.type.includes("image")) {
        form.options.value.forEach((option) => {
          if (option.key === "width" || option.key === "height") {
            option.hide = false;
          }
          // 图片组件使用图片展示，方便预览
          if (option.key === "url") {
            option.props!.listType = "picture-card";
          }
        });
        getImageInfoByFile(uploadParams.uploadFile.raw as Blob).then((img) => {
          form.data.value.width = img.width;
          form.data.value.height = img.height;
        });
      }
    },
  })
);
